import * as Collapsible from "@radix-ui/react-collapsible";
import { ChevronDown } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";

import { LoadingAnimation } from "~/components/deer-flow/loading-animation";
import { Markdown } from "~/components/deer-flow/markdown";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { InterviewStore } from "~/core/store";
import { parseJSON } from "~/core/utils";
import { cn } from "~/lib/utils";

export function QuestionGeneratorBlock({
  className,
  messageId,
}: {
  className?: string;
  messageId: string;
}) {
  const messageIds = InterviewStore.useStore(
    useShallow(
      (state) => state.questionGeneratorMessageIds.get(messageId) ?? [],
    ),
  );
  const contentRef = useRef<HTMLDivElement>(null);

  return (
    <div
      ref={contentRef}
      className={cn("grid w-full grid-cols-1 gap-4 pt-4 pb-8", className)}
    >
      {messageIds.map((messageId) => (
        <QuestionGeneratorItem key={messageId} messageId={messageId} />
      ))}
    </div>
  );
}

function QuestionGeneratorItem({ messageId }: { messageId: string }) {
  const message = InterviewStore.useMessage(messageId);
  const [open, setOpen] = useState(true); // 默认展开
  const isToolCalls = !!message?.toolCalls;

  const question = useMemo<{
    name?: string;
    content?: string;
  }>(() => {
    return isToolCalls ? {} : parseJSON(message?.content ?? "", {});
  }, [isToolCalls, message?.content]);

  if (isToolCalls) {
    return null;
  }

  return (
    <Collapsible.Root open={open} onOpenChange={setOpen} className="w-full">
      <Card>
        <CardHeader className="cursor-pointer px-4">
          <Collapsible.Trigger asChild>
            <CardTitle onClick={() => setOpen(!open)}>
              <div className="flex items-center justify-between">
                <div>{question.name}</div>
                <ChevronDown
                  className={`h-5 w-5 transition-transform duration-200 ${
                    open ? "rotate-180" : ""
                  }`}
                />
              </div>
            </CardTitle>
          </Collapsible.Trigger>
        </CardHeader>

        <Collapsible.Content className="data-[state=open]:animate-slideDown data-[state=closed]:animate-slideUp overflow-hidden">
          <CardContent>
            <Markdown animated checkLinkCredibility>
              {question.content}
            </Markdown>
            {message?.isStreaming && <LoadingAnimation className="my-12" />}
          </CardContent>
        </Collapsible.Content>
      </Card>
    </Collapsible.Root>
  );
}
